import Popup from "@/components/Popup/Popup";
import { defineComponent, reactive, ref } from "vue";
import styles from "./Add.module.less"
import to from "await-to-js";
import { CloudUploadOutlined, PlusOutlined } from "@ant-design/icons-vue";
import { $upload } from "@/apis/common/upload/upload";
import _ from "lodash";
import { message } from "ant-design-vue";

export default defineComponent({
  props: {
    service: {
      type: Object,
    }
  },
  emits: ["change"],
  setup(props, { expose, emit }) {

    const addPopupRef = ref(null as any);

    const state = reactive({
      type: '',
      form: {
        id: undefined, //分类id
        pid: null,  //上级id
        title: null, //课程标题
        cnSubtitle: null, //中文副标题
        enSubtitle: null, //英文副标题
        sort: null, //排序
        isLock: null, // 是否锁定
        isEnable: null, //状态
        coverUrl: null, //封面
        twoCoverUrl: null, //手机封面
        ipadCoverUrl: undefined, //ipad封面
        bgImageUrl: undefined, //背景图片
        ipadBgUrl: undefined, //ipad背景图片
      },
      options: {
        pid: [
          {
            id: 0,
            name: '作为一级菜单',
            children: [],
          }
        ],
      }
    } as any);

    //获取上级下拉列表
    const getTreeList = async () => {
      const [err, res]: any = await to(props.service?.tree());
      if (!err) {
        state.options.pid[0].children = res.data?.data || [];
      }
    }

    //获取详情
    const getDetail = async () => {
      const [err, res]: any = await to(props.service?.detail(state.form.id));
      if (!err) {
        const obj = res.data?.data || {};
        Object.keys(state.form).forEach(x => {
          if (x === 'cnSubtitle') {
            state.form.cnSubtitle = obj.csubtitle
          } else if (x === 'enSubtitle') {
            state.form.enSubtitle = obj.esubtitle
          } else {
            state.form[x] = obj[x]
          }
        })
      }
    }

    //打开弹窗
    const open = async ({ type, id }) => {
      state.type = type;
      state.form.id = id;
      await getTreeList();
      if (type === 'edit') {
        await getDetail();
      }
      addPopupRef.value.open()
    }

    const title_check = async (_rule: any, value: string) => {
      if (value === '') {
        return Promise.reject('请输入分类名称!');
      }
    };
    const cnSubtitle_check = async (_rule: any, value: string) => {
      if (value === '') {
        return Promise.reject('请输入中文副标题!');
      }
    };
    const enSubtitle_check = async (_rule: any, value: string) => {
      if (value === '') {
        return Promise.reject('请输入英文副标题!');
      }
    };
    const sort_check = async (_rule: any, value: string) => {
      if (value === '') {
        return Promise.reject('请输入排序!');
      }
    };
    //表单验证
    const rules = {
      title: [{ required: true, validator: title_check, trigger: 'change' }],
      cnSubtitle: [{ required: true, validator: cnSubtitle_check, trigger: 'change' }],
      enSubtitle: [{ required: true, validator: enSubtitle_check, trigger: 'change' }],
      sort: [{ required: true, validator: sort_check, trigger: 'change' }]
    }
    //上传
    const imageUpload = async (file, key) => {
      const formData = new FormData();
      formData.set('file', file);
      const [err, res]: any = await to($upload(formData))
      if (!err) {
        state.form[key] = res.data?.url || '';
      }
      return false;
    }
    //确认按钮loading
    const submitLoading = ref(false);

    //确定提交
    const submit = async () => {
      submitLoading.value = true;
      const params = _.cloneDeep(state.form);
      if (!params.pid) {
        message.error('请选择上级');
        return;
      }
      if (!params.title) {
        message.error('请输入分类名称');
        return;
      }
      if (!params.cnSubtitle) {
        message.error('请输入中文副标题');
        return;
      }
      if (!params.enSubtitle) {
        message.error('请输入英文副标题');
        return;
      }
      if (!params.sort) {
        message.error('请输入排序');
        return;
      }
      if (!params.isLock) {
        message.error('请选择是否锁定');
        return;
      }
      if (!params.isEnable) {
        message.error('请选择状态');
        return;
      }
      if (!params.coverUrl) {
        message.error('请上传封面');
        return;
      }
      if (!params.twoCoverUrl) {
        message.error('请上传手机封面');
        return;
      }
      const [err, res]: any = await to((state.type === 'edit' ? props.service?.edit : props.service?.add)(params))
      if (!err) {
        message.success(state.type === 'edit' ? '编辑成功' : '添加成功');
        addPopupRef.value.close();
        emit('change');
      }
      submitLoading.value = false;
    }

    expose({
      open
    })
    
    return () => (
      <Popup
        ref={addPopupRef}
        title={state.type === 'edit' ? "编辑分类" : '添加分类'}
        width="800px"
        oriState={state}
        v-slots={{
          footer: () => <>
            <a-button type="primary" loading={submitLoading.value} onClick={() => { submit() }}>确定</a-button>
            <a-button onClick={() => { addPopupRef.value.close() }}>取消</a-button>
          </>
        }}
      >
        <div class={styles.container}>
          <div class={styles.formBox}>
            <a-form model={state.form} rules={rules} label-col={{ style: { width: '150px', marginRight: '10px' } }} wrapper-col={{ span: 28 }}>
              <a-form-item label="上级" required name="pid">
                <a-tree-select
                  v-model:value={state.form.pid}
                  tree-data={state.options.pid}
                  placeholder="请选择上级"
                  fieldNames={{
                    label: 'name', value: 'id', children: 'children'
                  }}
                ></a-tree-select>
              </a-form-item>
              <a-form-item label="分类名称" required name="title">
                <a-input v-model:value={state.form.title} placeholder="请输入分类名称" />
              </a-form-item>
              <a-form-item label="中文副标题" required name="cnSubtitle">
                <a-input v-model:value={state.form.cnSubtitle} placeholder="请输入中文副标题" />
              </a-form-item>
              <a-form-item label="英文副标题" required name="enSubtitle">
                <a-input v-model:value={state.form.enSubtitle} placeholder="请输入英文副标题" />
              </a-form-item>
              <a-form-item required label="排序" name="sort">
                <a-input-number min={0} v-model:value={state.form.sort} placeholder="请输入排序" style="width: 50%" />
              </a-form-item>
              <a-form-item required label="是否锁定" name="isLock">
                <a-radio-group
                  v-model:value={state.form.isLock}
                  name="radioGroup"
                >
                  <a-radio value={0}>解锁</a-radio>
                  <a-radio value={1}>锁定</a-radio>
                </a-radio-group>
              </a-form-item>
              <a-form-item required label="状态" name="isEnable">
                <a-radio-group
                  v-model:value={state.form.isEnable}
                  name="radioGroup"
                >
                  <a-radio value={0}>正常</a-radio>
                  <a-radio value={1}>停用</a-radio>
                </a-radio-group>
              </a-form-item>
              <a-form-item label="封面" required name="coverUrl">
                <div class={styles.imageBox}>
                  {
                    state.form.coverUrl ?
                      <img src={state.form.coverUrl} /> :
                      <div class={styles.uploadBox}>
                        <PlusOutlined class={styles.icon} />
                      </div>
                  }
                  <a-upload
                    before-upload={(file) => imageUpload(file, "coverUrl")}
                    showUploadList={false}
                    name="file"
                  >
                    <div class={styles.uploadDemo}>
                      <CloudUploadOutlined class={styles.icon} />
                      <span>请上传封面</span>
                    </div>
                  </a-upload>
                </div>
              </a-form-item>
              <a-form-item label="手机封面" required name="twoCoverUrl">
                <div class={styles.imageBox}>
                  {
                    state.form.twoCoverUrl ?
                      <img src={state.form.twoCoverUrl} /> :
                      <div class={styles.uploadBox}>
                        <PlusOutlined class={styles.icon} />
                      </div>
                  }
                  <a-upload
                    before-upload={(file) => imageUpload(file, "twoCoverUrl")}
                    showUploadList={false}
                    name="file"
                  >
                    <div class={styles.uploadDemo}>
                      <CloudUploadOutlined class={styles.icon} />
                      <span>请上传封面</span>
                    </div>
                  </a-upload>
                </div>
              </a-form-item>
              <a-form-item label="ipad封面" name="ipadCoverUrl">
                <div class={styles.imageBox}>
                  {
                    state.form.ipadCoverUrl ?
                      <img src={state.form.ipadCoverUrl} /> :
                      <div class={styles.uploadBox}>
                        <PlusOutlined class={styles.icon} />
                      </div>
                  }
                  <a-upload
                    before-upload={(file) => imageUpload(file, "ipadCoverUrl")}
                    showUploadList={false}
                    name="file"
                  >
                    <div class={styles.uploadDemo}>
                      <CloudUploadOutlined class={styles.icon} />
                      <span>请上传封面</span>
                    </div>
                  </a-upload>
                </div>
              </a-form-item>
              <a-form-item label="背景图片" name="bgImageUrl">
                <div class={styles.imageBox}>
                  {
                    state.form.bgImageUrl ?
                      <img src={state.form.bgImageUrl} /> :
                      <div class={styles.uploadBox}>
                        <PlusOutlined class={styles.icon} />
                      </div>
                  }
                  <a-upload
                    before-upload={(file) => imageUpload(file, "bgImageUrl")}
                    showUploadList={false}
                    name="file"
                  >
                    <div class={styles.uploadDemo}>
                      <CloudUploadOutlined class={styles.icon} />
                      <span>请上传封面</span>
                    </div>
                  </a-upload>
                </div>
              </a-form-item>
              <a-form-item label="ipad背景图片" name="ipadBgUrl">
                <div class={styles.imageBox}>
                  {
                    state.form.ipadBgUrl ?
                      <img src={state.form.ipadBgUrl} /> :
                      <div class={styles.uploadBox}>
                        <PlusOutlined class={styles.icon} />
                      </div>
                  }
                  <a-upload
                    before-upload={(file) => imageUpload(file, "ipadBgUrl")}
                    showUploadList={false}
                    name="file"
                  >
                    <div class={styles.uploadDemo}>
                      <CloudUploadOutlined class={styles.icon} />
                      <span>请上传封面</span>
                    </div>
                  </a-upload>
                </div>
              </a-form-item>
            </a-form>
          </div>
        </div>
      </Popup>
    )
  }
})